import React from 'react';
import { connect } from 'dva';
import { Form, FormItem, Input, Button, Select,Icon,Upload,Modal,DatePicker  } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import request from '@/utils/request';
import { HOST_URL, IMG_URL } from '../../utils/utils';
import E from 'wangeditor'
import moment from 'moment/moment';

@connect(({ article, loading }) => ({
  article,
  loading: loading.effects['article/detail'],
}))

@Form.create()
class ArticleEdit extends React.Component {
  state = {
    preview: '',
    visible: false,
    id: '',
    article_title: '',
    article_describe: '',
    imageList: [],
    editorState:"",
    article_createTime:""
  };
  editor="";
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'article/fetchCategory',
      payload: { type: 'article' },
    });
    const elem = this.refs.editorElem
    this.editor = new E(elem)
    this.editor.customConfig.onchange = html => {
      this.setState({
        editorState: html
      })
    }
    this.editor.customConfig.customUploadImg = function (files, insert) {
      console.log(files.length)
      request('/api/oss/sign/images', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json;',
        },
      }).then(OSSSign => {
        let timestamp3 = new Date().getTime();
        const xhr = new XMLHttpRequest();
        let ossData = new FormData();
        ossData.append('name', timestamp3 + "" + files[0].name);
        ossData.append('OSSAccessKeyId', OSSSign.accessId);
        ossData.append('policy', OSSSign.policy);
        ossData.append('Signature', OSSSign.signature);
        ossData.append('callback', OSSSign.callback);
        ossData.append('key', `${OSSSign.dir}${OSSSign.policy.substr(0, 16)}${files[0].name}`);
        ossData.append('success_action_status', "200"); // 指定返回的状态码
        ossData.append('file', files[0]);
        xhr.open('POST', OSSSign.host);
        xhr.send(ossData);
        xhr.addEventListener('load', () => {
          console.log('response==>' + xhr.responseText);
          if (xhr.responseText.indexOf("Error") != -1) {
            alert(xhr.responseText.indexOf("Error"))
          } else {
            const response = JSON.parse(xhr.responseText);
            if (response.filename) {
              insert(IMG_URL + response.filename)
            } else {
              alert('服务器异常');
            }
          }
        });
        xhr.addEventListener('error', () => {
          alert('服务器异常');
        });
      });
    }
    this.editor.customConfig.zIndex = 1
    this.editor.create();
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.article.detail && nextProps.article.detail.articleId) {
      if(!this.state.editorState){
        this.editor.txt.html(nextProps.article.detail.body)
      }
      this.setState({
        id: nextProps.article.detail.articleId,
        article_title: nextProps.article.detail.title,
        article_describe: nextProps.article.detail.summary,
        categorys: nextProps.article.detail.categorys[0],
        authorId:nextProps.article.detail.authorId,
        tags: nextProps.article.detail.tags && nextProps.article.detail.tags.length > 0 ? nextProps.article.detail.tags.join('，') : '',
        categoryList:nextProps.article.categoryList,
        editorState:nextProps.article.detail.body,
        article_createTime:nextProps.article.detail.createTime,
        imageList: [{
          uid: 1,
          name: "name",
          status: "200",
          type: "type",
          result: "fileName",
          url: nextProps.article.detail.coverPic,
        }],
      });
    }
  }
  addArticle = () => {
    const { dispatch, form } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        dispatch({
          type: 'article/save',
          payload: {
            articleId: this.state.id,
            article_pic: this.state.imageList[0].url,
            article_detail: this.state.editorState,
            ...values,
            article_createTime: values.createTime && moment(values.createTime).format("YYYY-MM-DD HH:mm:ss")
          },
        });
      }
    });
  };
  uploadImageCallBack = (file) => {
    return new Promise(
      (resolve, reject) => {
        request('/api/oss/sign/images', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json;',
          },
        }).then(OSSSign => {
          let timestamp3 = new Date().getTime();
          const xhr = new XMLHttpRequest();
          let ossData = new FormData();
          ossData.append('name', file.name);
          ossData.append('OSSAccessKeyId', OSSSign.accessId);
          ossData.append('policy', OSSSign.policy);
          ossData.append('Signature', OSSSign.signature);
          ossData.append('callback', OSSSign.callback);
          ossData.append('key', `${OSSSign.dir}${OSSSign.policy.substr(0, 16)}${file.name}`);
          ossData.append('success_action_status', "200"); // 指定返回的状态码
          ossData.append('file', file);
          xhr.open('POST', OSSSign.host);
          xhr.send(ossData);
          xhr.addEventListener('load', () => {
            console.log('response==>' + xhr.responseText);
            const response = JSON.parse(xhr.responseText);
            if (response.filename) {
              resolve({
                data: {
                  link: IMG_URL + response.filename,
                },
              });
            } else {
              reject('服务器异常');
            }
          });
          xhr.addEventListener('error', () => {
            reject('服务器异常');
          });
        });
      },
    );
  };
  beforeUpload = file => {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onloadend = () => {
      request('/api/oss/sign/images', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json;',
        },
      }).then(OSSSign => {
        let timestamp3 = new Date().getTime();
        const xhr = new XMLHttpRequest();
        let ossData = new FormData();
        ossData.append('name', file.name);
        ossData.append('OSSAccessKeyId', OSSSign.accessId);
        ossData.append('policy', OSSSign.policy);
        ossData.append('Signature', OSSSign.signature);
        ossData.append('callback', OSSSign.callback);
        ossData.append('key', `${OSSSign.dir}${OSSSign.policy.substr(0, 16)}${file.name}`);
        ossData.append('success_action_status', "200"); // 指定返回的状态码
        ossData.append('file', file);
        xhr.open('POST', OSSSign.host);
        xhr.send(ossData);
        xhr.addEventListener('load', () => {
          console.log('response==>' + xhr.responseText);
          const response = JSON.parse(xhr.responseText);
          if (response.filename) {
            this.setState(({ imageList }) => ({
              imageList: [{
                uid: file.uid,
                name: file.name,
                status: file.status,
                type: file.type,
                result: file.name,
                url: IMG_URL + response.filename,
              }],
            }));
          } else {
            alert('服务器异常');
          }
        });
        xhr.addEventListener('error', () => {
          alert('服务器异常');
        });
      });
    };
    return false;
  };

  handlePreview = (file) => {
    this.setState({
      preview: file.url || file.thumbUrl,
      visible: true,
    });
  };
  handleCancel=()=>{
    this.setState({
      visible: false,
    });
  }
  render() {
    const {editorState, preview, visible, imageList } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };
    const uploadButton = (
      <div>
        <Icon type="plus"/>
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    const propsImgs = {
      onRemove: (file) => {
        this.setState(({ imageList }) => {
          const index = imageList.indexOf(file);
          const newFileList = imageList.slice();
          newFileList.splice(index, 1);
          return { imageList: newFileList };
        });
      },
      beforeUpload: this.beforeUpload,
      fileList: this.state.imageList,
      onPreview: this.handlePreview,
      accept: 'image/*',
      listType: 'picture-card',
    };
    const { form: { getFieldDecorator, getFieldValue },article:{categoryList} } = this.props;
    return (
      <PageHeaderWrapper
        title="编辑文章"
      >
        <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
          <Form.Item {...formItemLayout} label="标题">
            {getFieldDecorator('article_title', {
              initialValue: this.state.article_title,
              rules: [
                {
                  required: true,
                  message: '标题不能为空',
                },
              ],
            })(<Input placeholder="请输入标题"/>)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="作者Id">
            {getFieldDecorator('authorId', {
              initialValue: this.state.authorId,
              rules: [
                {
                  required: true,
                  message: '作者Id不能为空',
                },
              ],
            })(<Input placeholder="请输入作者名称"/>)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="文章类别">
            {getFieldDecorator('article_category', {
              initialValue: this.state.categorys,
              rules: [
                {
                  required: true,
                  message: '请选择文章类别',
                },
              ],
            })(<Select>
              {categoryList.map(category => <Select.Option value={category.name}
                                                               key={category.categoryId}>{category.name}</Select.Option>)}
            </Select>)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="文章标签">
            {getFieldDecorator('article_tag', {
              initialValue: this.state.tags,
              rules: [
                {
                  required: true,
                  message: '文章标签不能为空',
                },
              ],
            })(<Input placeholder="文章标签不能为空"/>)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="文章描述">
            {getFieldDecorator('article_describe', {
              initialValue: this.state.article_describe,
              rules: [
                {
                  required: true,
                  message: '文章描述不能为空',
                },
              ],
            })(
              <Input.TextArea
                style={{ minHeight: 32 }}
                placeholder="请输入文章描述"
                rows={4}
              />,
            )}
          </Form.Item>

          <Form.Item {...formItemLayout} label="createTime">
            {getFieldDecorator('createTime',{
              initialValue: this.state.article_createTime&&moment(this.state.article_createTime, "YYYY-MM-DD HH:mm:ss"),
            })(
              <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{width: '100%'}} placeholder="请输入"/>
            )}
          </Form.Item>
          <Form.Item {...formItemLayout} label="封面图">
            <div>
              <Upload {...propsImgs}>
                {
                  imageList.length >= 1 ? null : uploadButton
                }
              </Upload>
              <Modal visible={visible} footer={null} onCancel={this.handleCancel}>
                <img alt="example" style={{ width: '100%' }} src={preview}/>
              </Modal>
            </div>
          </Form.Item>
        </Form>
        <div ref="editorElem" style={{textAlign: 'left'}}>
        </div>
        <FooterToolbar style={{ width: '100%' }}>
          {/*{this.getErrorInfo()}*/}
          <Button type="primary" onClick={() => this.addArticle()} loading={this.props.submitting}>
            提交
          </Button>
        </FooterToolbar>
        {/*<Button className={styles.addButton} onClick={() => this.addArticle()}>提交</Button>*/}
      </PageHeaderWrapper>
    );
  }
}
export default ArticleEdit;
